﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Web;

namespace WeiXinSDK.Common
{
	public static class StringExt
	{

		public static T JsonDeserialize<T>(this string str)
		{
			return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
		}

		public static T XmlDeserialize<T>(this string str)
		{
			return (T)new XmlSerializer(typeof(T)).Deserialize(new StringReader(str));
		}

		public static string JoinStr(this IEnumerable<string> strList, string separator)
		{
			return string.Join(separator, strList);
		}
		public static string JoinStr(this IEnumerable<string> strList)
		{
			return string.Join("", strList);
		}
		public static string UrlEncode(this string str)
		{
			return HttpUtility.UrlEncode(str);
		}

		public static string UrlDecode(this string str)
		{
			return HttpUtility.UrlDecode(str);
		}
		public static string UrlDecode(this string str, Encoding encoding)
		{
			return HttpUtility.UrlDecode(str, encoding);
		}

		public static string FormatExt(this string str, params object[] param)
		{
			return string.Format(str, param);
		}

		/// <summary> 字符串默认MD5化 </summary>
		public static string MD5Default(this string str)
		{
			return str.GetUTF8Bytes().MD5Default().Select(m => m.ToString("X2")).JoinStr("");
		}

		public static string MD5GBK(this string str)
		{
			return str.GetGBKBytes().MD5Default().Select(m => m.ToString("X2")).JoinStr("");
		}

		public static string MD5Unicode(this string str)
		{
			return str.GetBytes(Encoding.Unicode).MD5Default().Select(m => m.ToString("X2")).JoinStr("");
		}

		public static byte[] GetUTF8Bytes(this string str)
		{
			return str.GetBytes(Encoding.UTF8);
		}

		public static byte[] GetGBKBytes(this string str)
		{
			return str.GetBytes(Encoding.GetEncoding("GBK"));
		}

		public static byte[] GetBytes(this string str, Encoding encoding)
		{
			return encoding.GetBytes(str);
		}
	}
}
